package cn.edkuir.ware.service.impl;

import cn.edkuir.common.constant.WareConstant;
import cn.edkuir.ware.entity.PurchaseDetailEntity;
import cn.edkuir.ware.service.PurchaseDetailService;
import cn.edkuir.ware.service.WareSkuService;
import cn.edkuir.ware.vo.MergeVo;
import cn.edkuir.ware.vo.PurchaseDoneItemVo;
import cn.edkuir.ware.vo.PurchaseDoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edkuir.common.utils.PageUtils;
import cn.edkuir.common.utils.Query;

import cn.edkuir.ware.dao.PurchaseDao;
import cn.edkuir.ware.entity.PurchaseEntity;
import cn.edkuir.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceived(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    //合并整单
    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null) {
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.CREATE.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 确认采购单状态是0或1

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            //已分配
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        //更新修改时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    //领取采购单
    @Override
    public void receive(List<Long> purchaseIdList) {
        //1.确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = purchaseIdList.stream().map(purchaseId -> this.getById(purchaseId)
        ).filter(item -> item.getStatus() == WareConstant.PurchaseStatus.CREATE.getCode()
                || item.getStatus() == WareConstant.PurchaseStatus.ASSIGNED.getCode()
        ).map(item -> {
            item.setStatus(WareConstant.PurchaseStatus.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2.改变采购单的状态
        this.updateBatchById(purchaseEntities);

        //3.改变采购项的状态
        purchaseEntities.forEach(item -> {
            //3.1)找到每个采购单对应的所有采购需求
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        });
    }


    //完成采购
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        //1.改变采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        for (PurchaseDoneItemVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //如果采购失败则设置状态为"失败"
            if(item.getStatus() == WareConstant.PurchaseDetailStatus.FAILURE.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.FINISH.getCode());

                //3.将成功采购的入库
                //查询采购项详细信息
                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                //skuId, 数量, 仓库id
                wareSkuService.addStock(detail.getSkuId(), detail.getSkuNum(), detail.getWareId());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //2.改变采购单状态
        Long id = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        //设置id和status
        purchaseEntity.setId(id);
        Integer code = flag ? WareConstant.PurchaseStatus.FINISH.getCode() : WareConstant.PurchaseStatus.HASERROR.getCode();
        purchaseEntity.setStatus(code);
        this.updateById(purchaseEntity);

    }

}